//
//  ViewController.m
//  here
//
//  Created by 杜承玖 on 2/10/15.
//  Copyright (c) 2015 redianying. All rights reserved.
//

#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "Function.h"

@interface ViewController ()

@property (nonatomic, assign) BOOL switchState; //开关状态
@property (nonatomic, assign) BOOL backOrFront;//后置闪光灯显示还是前置的屏幕闪烁

@property (nonatomic, strong) UIColor * defaultColor;

@property (nonatomic, strong) NSTimer * timer;

@end

@implementation ViewController

- (IBAction)back:(id)sender {
    [self off];
    [_timer invalidate];
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)off {
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    [device lockForConfiguration:nil];
    [device setTorchMode: AVCaptureTorchModeOff];
    [device unlockForConfiguration];
}

- (IBAction)flip:(id)sender {
    _backOrFront = !_backOrFront;
    
    if (_backOrFront) {
        self.view.backgroundColor = _defaultColor;
    } else {
        [self off];
    }
    [self setSwitchState:_switchState];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    /*
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    [self setNeedsStatusBarAppearanceUpdate];
     */
    
    _defaultColor = [Function colorWithHexString:@"1D2C39"];
    CGFloat delay = 0.19; //0.18
    _timer = [NSTimer scheduledTimerWithTimeInterval:delay target:self selector:@selector(flash) userInfo:nil repeats:YES];
}

- (void)setSwitchState:(BOOL)switchState {
    _switchState = switchState;
    
    if ( !_backOrFront ) {
        self.view.backgroundColor = switchState ? _defaultColor : _color;
        //self.view.backgroundColor = switchState ? [UIColor blackColor] : [UIColor whiteColor];
    } else {
        AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        if (![device hasTorch]) {
            NSLog(@"no torch");
        } else {
            [device lockForConfiguration:nil];
            if (!_switchState) {
                [device setTorchMode: AVCaptureTorchModeOn];
            } else {
                [device setTorchMode: AVCaptureTorchModeOff];
            }
            [device unlockForConfiguration];
        }
    }
}

- (void)flash {
    self.switchState = !self.switchState;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
